package com.example.myys.ui.page.ysPage

import android.app.Activity
import android.content.pm.ActivityInfo
import android.view.SurfaceView
import android.view.View
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.NativeKeyEvent
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import com.example.myys.R
import com.example.myys.network.HttpClient
import com.example.myys.ui.StateHandler
import com.example.myys.util.ResizeMode
import com.example.myys.util.adaptiveLayout
import com.example.myys.util.aspectRatio
import com.example.myys.viewModel.ysModel.VideoPlayViewModel
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


//隐藏系统栏
private fun hideSystemBars(view: View, activity: Activity) {
    activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    val windowInsetsController = WindowCompat.getInsetsController(activity.window, view)
    // Configure the behavior of the hidden system bars
    windowInsetsController.systemBarsBehavior =
        WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    // Hide both the status bar and the navigation bar
    windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
}

//显示系统栏
private fun showSystemBars(view: View, activity: Activity) {
    activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
    val windowInsetsController = WindowCompat.getInsetsController(activity.window, view)
    // Show both the status bar and the navigation bar
    windowInsetsController.show(WindowInsetsCompat.Type.systemBars())
}

@OptIn(ExperimentalFoundationApi::class, UnstableApi::class)
@Composable
fun YsViedoPlay(
    onBackClick: () -> Unit,
    dataBean: String,
    activity: Activity
) {
    val viewModel: VideoPlayViewModel = viewModel()
    //播放数据
    val animeVideoState by viewModel.videoState.collectAsState()

    //控制显示
    var isControlUiVisible by remember {
        mutableStateOf(false)
    }
    //选集显示
    var isXjUiVisible by remember {
        mutableStateOf(false)
    }
    //播放状态
    var playerState by remember {
        mutableStateOf("")
    }
    //进度
    var sliderPosition by remember { mutableFloatStateOf(0f) }
    var bufferedPercentage by remember { mutableFloatStateOf(0f) }
    var dangQianJingdu by remember {
        mutableLongStateOf(0L)
    }
    var zongJingdu by remember {
        mutableLongStateOf(0L)
    }
    //前进后退滑动
    var offsetX by remember {
        mutableStateOf(0f)
    }
    val draggableState = rememberDraggableState { offsetX = it }


    //焦点
    val xjFocus = remember { FocusRequester() }
    val mainFocus = remember { FocusRequester() }

    val context = LocalContext.current
    val view = LocalView.current
    // 使用rememberCoroutineScope来持有CoroutineScope的引用
    val coroutineScope = rememberCoroutineScope()

    val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

    val loadControl = DefaultLoadControl.Builder()
        .setBufferDurationsMs(5000, 20000, 1000, 5000)
        .build()
    val okhttpDataSourceFactory = OkHttpDataSource.Factory(HttpClient.client!!)
    val dataSourceFactory =
        DefaultDataSource.Factory(context, /* baseDataSourceFactory= */ okhttpDataSourceFactory)

    val exoplayer = remember {
        ExoPlayer.Builder(context)
            .setMediaSourceFactory(
                DefaultMediaSourceFactory(context).setDataSourceFactory(dataSourceFactory)
            )
            .setHandleAudioBecomingNoisy(true)
            .setLoadControl(loadControl)
            .setSeekForwardIncrementMs(10 * 1000)
            .setSeekBackIncrementMs(10 * 1000)
            .build()
    }
    /*exoplayer.prepare()
    exoplayer.play()*/

    Box(
        modifier = Modifier
            .background(Color.Black)
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = {
                        isControlUiVisible = !isControlUiVisible
                        isXjUiVisible = false
                    },
                    onDoubleTap = {
                        if (exoplayer.isPlaying) exoplayer.pause() else exoplayer.play()
                    }
                )
            },
        contentAlignment = Alignment.Center
    ) {
        StateHandler(
            state = animeVideoState,
            onLoading = {
                view.keepScreenOn = true
                Box(
                    modifier = Modifier
                        .background(Color.Black)
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            },
            onFailure = {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Spacer(modifier = Modifier.padding(vertical = 8.dp))
                    Text(
                        text = stringResource(id = R.string.txt_empty_result),
                        color = Color.White,
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Spacer(modifier = Modifier.padding(vertical = 8.dp))
                    OutlinedButton(onClick = onBackClick) {
                        Text(text = stringResource(id = R.string.back), color = Color.White)
                    }
                }
            }
        ) { resource ->
            resource.data?.let { video ->
                LaunchedEffect(video) {
                    exoplayer.setMediaItem(MediaItem.fromUri(video.url))
                    exoplayer.prepare()
                    exoplayer.playWhenReady = true
                    mainFocus.requestFocus()
                    Toast.makeText(context, video.url, Toast.LENGTH_SHORT).show()
                }
                AndroidView(factory = { ctx ->
                    SurfaceView(context).also {
                        exoplayer.setVideoSurfaceView(it)
                    }
                }, modifier = Modifier
                    .adaptiveLayout(
                        aspectRatio = exoplayer.videoSize.aspectRatio(),
                        resizeMode = ResizeMode.Fit
                    )
                    .onKeyEvent { keyEvent ->
                        if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_DOWN) {
                            //向下按
                            //显示控制
                            isControlUiVisible = !isControlUiVisible
                            if (!isControlUiVisible) {
                                mainFocus.requestFocus()
                            }
                            isXjUiVisible = false
                            true
                        } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_CENTER) {
                            if (exoplayer.isPlaying) exoplayer.pause() else exoplayer.play()
                            true
                        } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_RIGHT) {
                            val progress = 30000L + exoplayer.currentPosition
                            exoplayer.seekTo(progress)
                            Toast
                                .makeText(context, "前进30s", Toast.LENGTH_SHORT)
                                .show()
                            true
                        } else if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_LEFT) {
                            val progress = -30000L + exoplayer.currentPosition
                            exoplayer.seekTo(progress)
                            Toast
                                .makeText(context, "后退30s", Toast.LENGTH_SHORT)
                                .show()
                            true
                        } else {
                            false
                        }
                    }
                    .draggable(
                        state = draggableState,
                        orientation = Orientation.Horizontal,
                        onDragStopped = { velocity ->
                            if (offsetX < 0) {
                                Toast
                                    .makeText(context, "后退10s", Toast.LENGTH_SHORT)
                                    .show()
                                exoplayer.seekBack()
                            }
                            if (offsetX > 0) {
                                Toast
                                    .makeText(context, "前进10s", Toast.LENGTH_SHORT)
                                    .show()
                                exoplayer.seekForward()
                            }
                        })
                    .focusRequester(mainFocus)
                    .focusable()
                )
                AnimatedVisibility(
                    visible = isControlUiVisible,
                    enter = fadeIn(),
                    exit = fadeOut()
                ) {
                    Box(modifier = Modifier.fillMaxSize()) {
                        Row(
                            modifier = Modifier
                                .align(Alignment.TopStart)
                                .padding(3.dp)
                        ) {
                            Text(text = video.movieName, color = Color.White)
                            Text(text = "--", color = Color.White)
                            Text(text = video.name, color = Color.White)
                        }
                        Column(
                            modifier = Modifier
                                .align(Alignment.BottomCenter)
                                .fillMaxWidth()
                                .background(Color.Black.copy(0.6f)),
                            verticalArrangement = Arrangement.spacedBy(0.dp),
                            horizontalAlignment = Alignment.Start
                        ) {
                            Row(
                                modifier = Modifier
                                    .height(40.dp)
                                    .fillMaxWidth(),
                                horizontalArrangement = Arrangement.Center
                            ) {
                                Box(
                                    modifier = Modifier.weight(1f),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Slider(
                                        value = bufferedPercentage,
                                        onValueChange = {},
                                        enabled = false,
                                        valueRange = 0f..100f,
                                        colors = SliderDefaults.colors(
                                            disabledThumbColor = Color.Transparent,
                                            disabledActiveTrackColor = Color.White.copy(alpha = 0.6f),
                                        ),
                                    )
                                    Slider(
                                        value = sliderPosition,
                                        onValueChange = {
                                            sliderPosition = it
                                            exoplayer.seekTo((sliderPosition * zongJingdu).toLong())
                                        },
                                        colors = SliderDefaults.colors(
                                            thumbColor = FloatingActionButtonDefaults.containerColor,
                                            activeTrackColor = FloatingActionButtonDefaults.containerColor,
                                            inactiveTrackColor = Color.Transparent
                                        )
                                    )
                                }
                                /* Slider(
                                     modifier = Modifier.weight(1f),
                                     value = sliderPosition,
                                     onValueChange = {
                                         sliderPosition = it
                                         exoplayer.seekTo((sliderPosition * zongJingdu).toLong())
                                     }
                                 )*/
                                Text(
                                    text = formatTimestamp(dangQianJingdu / 1000) + "/" + formatTimestamp(
                                        zongJingdu / 1000
                                    ),
                                    color = Color.White
                                )
                            }
                            playerControl(
                                modifier = Modifier.onKeyEvent { keyEvent ->
                                    if (keyEvent.nativeKeyEvent.action == NativeKeyEvent.ACTION_DOWN && keyEvent.nativeKeyEvent.keyCode == NativeKeyEvent.KEYCODE_DPAD_UP) {
                                        //向下按
                                        //显示控制
                                        isControlUiVisible = !isControlUiVisible
                                        if (!isControlUiVisible) {
                                            mainFocus.requestFocus()
                                        }
                                        isXjUiVisible = false
                                        true
                                    }
                                    false
                                },
                                onPlayerChick = { if (exoplayer.isPlaying) exoplayer.pause() else exoplayer.play() },
                                onEsidosClicke = {
                                    isXjUiVisible = !isXjUiVisible
                                    if (isXjUiVisible) {
                                        coroutineScope.launch {
                                            delay(1000)
                                            xjFocus.requestFocus()
                                        }
                                    }
                                },
                                onNextPlay = {
                                    exoplayer.pause()
                                    viewModel.next()
                                },
                                onPreviousPlay = {
                                    exoplayer.pause()
                                    viewModel.previous()
                                }
                            )
                        }
                    }
                }
                AnimatedVisibility(
                    visible = isXjUiVisible,
                    enter = fadeIn(),
                    exit = fadeOut()
                ) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.CenterEnd
                    ) {
                        var selectedEpisodeIndex by remember {
                            mutableStateOf(viewModel.playIndex)
                        }
                        LazyRow(
                            modifier = Modifier
                                .fillMaxHeight(0.9f)
                                .width(400.dp)
                                .background(Color.Black.copy(0.6f))
                                .focusRequester(xjFocus),
                        ) {
                            itemsIndexed(video.chapter) { index, item ->
                                Column {
                                    Text(
                                        modifier = Modifier.background(
                                            if (viewModel.playSourceIndex == index) Color.Blue else Color.Transparent
                                        ),
                                        text = item.name, color = Color.White,
                                    )
                                    LazyColumn(
                                        modifier = Modifier.width(200.dp),
                                        state = rememberLazyListState(
                                            initialFirstVisibleItemIndex = selectedEpisodeIndex,
                                            -200
                                        )
                                    ) {
                                        itemsIndexed(item.episodes) { indexI, itemI ->
                                            Button(
                                                modifier = Modifier.fillMaxWidth(),
                                                onClick = {
                                                    exoplayer.pause()
                                                    viewModel.playIndex = indexI
                                                    viewModel.playSourceIndex = index
                                                    viewModel.getVideo(indexI)
                                                    isXjUiVisible = false
                                                }) {
                                                Text(
                                                    text = itemI.name,
                                                    color = if (indexI == selectedEpisodeIndex) Color.White else Color.Black
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        /*LazyColumn(
                          modifier = Modifier
                            .fillMaxHeight(0.9f)
                            .width(200.dp)
                            .background(Color.Black.copy(0.3f))
                            .focusRequester(xjFocus),
                          state = rememberLazyListState(initialFirstVisibleItemIndex = selectedEpisodeIndex, -200)
                        ) {
                          itemsIndexed(video.chapter) {index,item->
                            Button(
                              modifier = Modifier.fillMaxWidth(),
                              onClick = {
                                viewModel.playIndex=index
                                viewModel.getVideo(index)
                              }) {
                              Text(
                                color = if (index == selectedEpisodeIndex) MaterialTheme.colorScheme.primary else Color.White,
                                text = item.name)
                            }
                          }
                        }*/
                    }
                }
            }
        }

        if (playerState.isNotEmpty()) {
            //播放状态展示
            Text(
                modifier = Modifier.align(Alignment.Center),
                text = playerState,
                color = Color.White
            )
        }
    }

    LaunchedEffect(Unit) {
        exoplayer.addListener(
            object : Player.Listener {
                override fun onIsPlayingChanged(isPlaying: Boolean) {
                    super.onIsPlayingChanged(isPlaying)
                    if (isPlaying) {
                        playerState = ""
                    } else {
                        if (playerState.isEmpty()) {
                            playerState = "播放暂停"
                        }
                    }
                }

                override fun onPlaybackStateChanged(playbackState: Int) {
                    super.onPlaybackStateChanged(playbackState)
                    when (playbackState) {
                        Player.STATE_READY -> {
                            // 播放器准备好播放时的处理逻辑
                            zongJingdu = exoplayer.duration
                            coroutineScope.launch {
                                while (true) {
                                    delay(1000)
                                    dangQianJingdu = exoplayer.currentPosition
                                    bufferedPercentage = exoplayer.bufferedPercentage.toFloat()
                                    sliderPosition = dangQianJingdu.toFloat() / zongJingdu
                                }
                            }
                        }

                        Player.STATE_BUFFERING -> {
                            // 播放器正在缓冲时的处理逻辑
                            playerState = "播放缓冲中"
                        }

                        Player.STATE_ENDED -> {
                            // 播放结束时的处理逻辑
                            playerState = "播放结束"
                        }
                    }
                }

                override fun onPlayerError(error: PlaybackException) {
                    super.onPlayerError(error)
                    playerState = "播放失败"
                }
            }
        )
        viewModel.setDataBean(dataBean)
        hideSystemBars(view, activity)
        view.keepScreenOn = true
    }
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> exoplayer.play()
                Lifecycle.Event.ON_STOP -> exoplayer.pause()
                else -> Unit
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            exoplayer.pause()
            exoplayer.release()
            coroutineScope.cancel()
            showSystemBars(view, activity)
            view.keepScreenOn = false
        }
    }

}

@Composable
fun playerControl(
    modifier: Modifier,
    onPlayerChick: () -> Unit,
    onEsidosClicke: () -> Unit,
    onNextPlay: () -> Unit,
    onPreviousPlay: () -> Unit,
) {
    //焦点
    val bfFocus = remember { FocusRequester() }

    LaunchedEffect(Unit) {
        delay(1000)
        bfFocus.requestFocus()
    }

    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        val isFocus = remember { mutableStateListOf(false, false, false, false) }

        OutlinedButton(onClick = onPlayerChick,
            modifier = Modifier
                .focusRequester(bfFocus)
                .onFocusChanged {
                    isFocus[0] = it.isFocused
                }
                .background(if (isFocus[0]) Color.Blue else Color.Transparent)) {
            Text(text = "播放")
        }
        OutlinedButton(onClick = onNextPlay,
            modifier = Modifier
                .onFocusChanged {
                    isFocus[1] = it.isFocused
                }
                .background(if (isFocus[1]) Color.Blue else Color.Transparent)) {
            Text(text = "下一集")
        }
        OutlinedButton(onClick = onPreviousPlay,
            modifier = Modifier
                .onFocusChanged {
                    isFocus[2] = it.isFocused
                }
                .background(if (isFocus[2]) Color.Blue else Color.Transparent)) {
            Text(text = "上一集")
        }
        OutlinedButton(onClick = onEsidosClicke,
            modifier = Modifier
                .onFocusChanged {
                    isFocus[3] = it.isFocused
                }
                .background(if (isFocus[3]) Color.Blue else Color.Transparent)) {
            Text(text = "选集")
        }
    }
}

private fun formatTimestamp(timestampInSeconds: Long): String {
    var hour = 0L
    var minutes = timestampInSeconds / 60
    if (minutes >= 60) {
        hour = minutes / 60
        minutes = minutes % 60
    }
    val seconds = timestampInSeconds % 60
    if (hour == 0L) {
        return "%02d:%02d".format(minutes, seconds)
    } else {
        return "%02d:%02d:%02d".format(hour, minutes, seconds)
    }
}